import { Prisma } from '@prisma/client';
import prisma from '@/server/lib/prisma';
import { MenuSchema } from '@/server/lib/zodSchema';

export default defineEventHandler(async (event) => {
  try {
    const body = await readBody(event);
    MenuSchema.parse(body); // 校验参数

    // 菜单名称是否存在
    const isMenuName = await prisma.sys_menu.findFirst({
      where: {
        menuName: body.menuName
      }
    })
    if (isMenuName) {
      return {
        code: 400,
        msg: '菜单名称已存在',
      }
    }

    // 参数
    const data: Prisma.sys_menuCreateInput = {
      parentId: Number(body.parentId || 0),
      menuName: body.menuName,
      menuEnName: body.menuEnName,
      icon: body.icon,
      orderNum: body.orderNum,
      menuType: body.menuType,
      url: body.url,
      target: body.target,
      visible: body.visible,
      remark: body.remark,
    }
    const result = await prisma.sys_menu.create({
      data,
    })
    return {
      code: 200,
      data: result,
      msg: '创建成功'
    }
  } catch (error: any) {
    const err = JSON.parse(error);
    return {
      code: 400,
      msg: err[0].message || '未知错误',
    }
  } finally {
    await prisma.$disconnect(); // 关闭连接
  }
})